package com.itheima.service.impl;

import com.itheima.mapper.RoleMapper;
import com.itheima.mapper.UserMapper;
import com.itheima.domain.Role;
import com.itheima.domain.User;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service("userService")
public class UserServiceImpl implements UserService {

    @Resource(name = "userMapper")
    private UserMapper userMapper;
    @Resource(name = "roleMapper")
    private RoleMapper roleMapper;



    @Override
    public List<User> list() {
        List<User> userList = userMapper.findAll();
        //封装userList中的每一个User的roles数据
        for(User user:userList){
            //获得user的id
            long id = user.getId();
            //将id作为参数 查询当前userId对应的Role集合数据
            List<Role> roles = roleMapper.findRoleByUserId(id);
            user.setRoles(roles);
        }
        return userList;
    }

    @Override
    public void save(User user, Long[] roleIds) {
        //第一步 向sys_user表中存储数据
        userMapper.save(user);
        Long userId = user.getId();
        //第二步 向sys_user_role关系表中存储多条数据
        for (Long roleId : roleIds) {
            userMapper.saveUserRoleRel(userId,roleId);
        }

    }

    @Override
    public void del(Long userId) {
        //1.删除关系表中的数据
        userMapper.delUserRoleRel(userId);
        //2.删除user表的数据
        userMapper.del(userId);
    }

    @Override
    public User login(String username, String password) {
        try {
            User user = userMapper.findByUsernameAndPassword(username,password);
            return user;
        }catch (EmptyResultDataAccessException e){
            return null;
        }
    }
}
